import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/models/evaluation/evaluationOverviewResult.dart';
import 'package:ichinesereader/models/report/evaluationLevelChartData.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:get/get.dart';
import 'dart:math' as math;

class EvaluationStackedLineChart extends StatelessWidget {
  EvaluationStackedLineChart(
      {Key? key,
      required this.levelChartData,
      required this.studentLists,
      required this.chartTitle,
      required this.xLabel,
      this.levelStandard = 'ICR',
      required this.yLabel})
      : super(key: key);
  final List<EvaluationLevelChart> levelChartData;
  final String chartTitle;
  final String xLabel;
  final String yLabel;
  final List<StudentList> studentLists;
  final String? levelStandard;

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation teacher stacked lines chart Widget');
    //TooltipBehavior _tooltipbehavior = TooltipBehavior(enable: true);

    TooltipBehavior _tooltipbehavior = TooltipBehavior(
        enable: true,
        duration: 1800,
        //format: 'Level: ${point.x} \n Score: point.y',
        builder: (dynamic data, dynamic point, dynamic series, int pointIndex,
            int seriesIndex) {
          return Padding(
            padding: const EdgeInsets.all(2.0),
            child: Container(
                color: Colors.grey[100],
                child: Text(
                    '${series.name}\nLevel: ${point.x.toString()} \nScore: ${point.y.toString()}')),
          );
        });

    List<StackedLineSeries<EvaluationLevelChart, String>> _buildSeries() {
      List<StackedLineSeries<EvaluationLevelChart, String>> series = [];
      series.add(StackedLineSeries<EvaluationLevelChart, String>(
        groupName: 'class',
        name: 'Class Average'.tr,
        dashArray: <double>[5, 5],
        dataSource: levelChartData,
        xValueMapper: (EvaluationLevelChart data, _) =>
            data.level.replaceAll('ACTFLLevel.', ''),
        yValueMapper: (EvaluationLevelChart data, _) {
          if (this.chartTitle == 'Listening') {
            return data.listening;
          } else if (this.chartTitle == 'Reading') {
            return data.reading;
          } else if (this.chartTitle == 'Writing') {
            return data.writing;
          } else if (this.chartTitle == 'Speaking') {
            return data.speaking;
          } else if (this.chartTitle == 'AI Speaking') {
            return data.aiSpeaking;
          } else {
            return data.translate;
          }
        },
        color: hexStringToHexInt('#ed5565'),
        dataLabelSettings: DataLabelSettings(isVisible: false),
      ));

      studentLists.forEach((student) {
        List<EvaluationLevelChart> chartData = [];
        if (levelStandard == 'ICR' && student.icrLevel!.isNotEmpty) {
          student.icrLevel?.forEach((item) {
            EvaluationLevelChart chart = EvaluationLevelChart(
                item.level.toString(),
                item.listeningAccuracy! / 10,
                item.speakingScore?.toDouble(),
                item.speakingAiScore! / 10,
                item.readingAccuracy! / 10,
                item.writingScore?.toDouble(),
                item.translateScore! / 10);
            chartData.add(chart);
          });
        }

        if (levelStandard == 'ACFTL' && student.actflLevel!.isNotEmpty) {
          student.actflLevel?.forEach((item) {
            EvaluationLevelChart chart = EvaluationLevelChart(
                item.level.toString(),
                item.listeningAccuracy! / 10,
                item.speakingScore?.toDouble(),
                item.speakingAiScore! / 10,
                item.readingAccuracy! / 10,
                item.writingScore?.toDouble(),
                0);
            chartData.add(chart);
          });
        }
        var studentItem = StackedLineSeries<EvaluationLevelChart, String>(
          groupName: student.userName,
          name: student.userName,
          dashArray: <double>[5, 5],
          dataSource: chartData,
          xValueMapper: (EvaluationLevelChart data, _) =>
              data.level.replaceAll('ACTFLLevel.', ''),
          yValueMapper: (EvaluationLevelChart data, _) {
            if (this.chartTitle == 'Listening') {
              return data.listening;
            } else if (this.chartTitle == 'Reading') {
              return data.reading;
            } else if (this.chartTitle == 'Writing') {
              return data.writing;
            } else if (this.chartTitle == 'Speaking') {
              return data.speaking;
            } else if (this.chartTitle == 'AI Speaking') {
              return data.aiSpeaking;
            } else {
              return data.translate;
            }
          },
          color: Color((math.Random().nextDouble() * 0xFFFFFF).toInt())
              .withOpacity(1.0),
          dataLabelSettings: DataLabelSettings(isVisible: false),
        );

        series.add(studentItem);
      });

      return series;
    }

    return SfCartesianChart(
      title: ChartTitle(
        text: this.chartTitle.tr,
        textStyle: TextStyle(
            color: Get.isDarkMode
                ? Get.theme.primaryColorDark
                : Get.theme.primaryColorLight),
      ),
      legend: Legend(isVisible: true, position: LegendPosition.top),
      tooltipBehavior: _tooltipbehavior,
      primaryXAxis: CategoryAxis(
        plotBands: levelStandard == 'ICR'
            ? Constants.plotbandIChineseReader
                .where((element) => element.start < 16)
                .toList()
            : Constants.plotbandACTFL
                .where((element) => element.start < 5)
                .toList(),
      ),
      primaryYAxis: NumericAxis(
        title: AxisTitle(text: this.xLabel),
        minimum: 0,
        maximum: 10,
        // this.chartTitle == 'Writing' || this.chartTitle == 'Speaking'
        //     ? 10
        //     : 100,
        interval: 1,
        // this.chartTitle == 'Writing' || this.chartTitle == 'Speaking'
        //     ? 1
        //     : 10,
      ),
      series: _buildSeries(),
      // <ChartSeries>[
      //   StackedLineSeries<EvaluationLevelChart, String>(
      //     groupName: 'class',
      //     name: 'Class Average'.tr,
      //     dashArray: <double>[5, 5],
      //     dataSource: levelChartData,
      //     xValueMapper: (EvaluationLevelChart data, _) => data.level,
      //     yValueMapper: (EvaluationLevelChart data, _) => data.listening,
      //     color: hexStringToHexInt('#ed5565'),
      //     dataLabelSettings: DataLabelSettings(isVisible: false),
      //   ),
      //   // StackedLineSeries<EvaluationLevelChart, String>(
      //   //   groupName: 'reading',
      //   //   name: 'Reading'.tr,
      //   //   dashArray: <double>[5, 5],
      //   //   dataSource: levelChartData,
      //   //   xValueMapper: (EvaluationLevelChart data, _) => data.level,
      //   //   yValueMapper: (EvaluationLevelChart data, _) => data.reading,
      //   //   color: hexStringToHexInt('#23c6c8'),
      //   //   dataLabelSettings: DataLabelSettings(isVisible: false),
      //   // ),
      // ],
    );
  }
}

class EvaluationStackedLineChartForStudent extends StatelessWidget {
  EvaluationStackedLineChartForStudent(
      {Key? key,
      required this.levelChartData,
      required this.chartTitle,
      required this.xLabel,
      required this.yLabel,
      this.mode = 'evaluation'})
      : super(key: key);
  final List<EvaluationLevelChart> levelChartData;
  final String chartTitle;
  final String xLabel;
  final String yLabel;
  final String mode;

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation student stacked lines chart Widget');
    TooltipBehavior _tooltipbehavior = TooltipBehavior(enable: true);

    return SfCartesianChart(
        title: ChartTitle(
          alignment: ChartAlignment.center,
          text: this.chartTitle.tr,
          textStyle: TextStyle(
            color: Get.isDarkMode ? Colors.white : Colors.black,
          ),
        ),
        legend: Legend(
          isVisible: true,
          position: LegendPosition.top,
          textStyle:
              TextStyle(color: Get.isDarkMode ? Colors.white : Colors.black),
        ),
        tooltipBehavior: _tooltipbehavior,
        primaryXAxis: CategoryAxis(
          plotBands: Constants.plotbandIChineseReader
              .where((element) => element.start < 16)
              .toList(),
        ),
        primaryYAxis: NumericAxis(
            title: AxisTitle(text: this.xLabel),
            minimum: 0,
            maximum: 10,
            interval: 1),
        series: this.mode == 'quickReview'
            ? <ChartSeries>[
                StackedLineSeries<EvaluationLevelChart, String>(
                  groupName: 'Speaking',
                  name: 'Speaking'.tr,
                  dashArray: <double>[5, 5],
                  dataSource: levelChartData,
                  xValueMapper: (EvaluationLevelChart data, _) =>
                      data.level.replaceAll('ACTFLLevel.', ''),
                  yValueMapper: (EvaluationLevelChart data, _) => data.speaking,
                  color: hexStringToHexInt('#f8ac59'),
                  dataLabelSettings: DataLabelSettings(isVisible: false),
                ),
                StackedLineSeries<EvaluationLevelChart, String>(
                  groupName: 'Writing',
                  name: 'Writing'.tr,
                  dashArray: <double>[5, 5],
                  dataSource: levelChartData,
                  xValueMapper: (EvaluationLevelChart data, _) =>
                      data.level.replaceAll('ACTFLLevel.', ''),
                  yValueMapper: (EvaluationLevelChart data, _) => data.writing,
                  color: hexStringToHexInt('#1ab394'),
                  dataLabelSettings: DataLabelSettings(isVisible: false),
                ),
                StackedLineSeries<EvaluationLevelChart, String>(
                  groupName: 'AISpeaking',
                  name: 'AI Speaking'.tr,
                  dashArray: <double>[5, 5],
                  dataSource: levelChartData,
                  xValueMapper: (EvaluationLevelChart data, _) =>
                      data.level.replaceAll('ACTFLLevel.', ''),
                  yValueMapper: (EvaluationLevelChart data, _) =>
                      data.aiSpeaking,
                  color: hexStringToHexInt('#9d98f4'),
                  dataLabelSettings: DataLabelSettings(isVisible: false),
                ),
                StackedLineSeries<EvaluationLevelChart, String>(
                  groupName: 'Translating',
                  name: 'Translating'.tr,
                  dashArray: <double>[5, 5],
                  dataSource: levelChartData,
                  xValueMapper: (EvaluationLevelChart data, _) =>
                      data.level.replaceAll('ACTFLLevel.', ''),
                  yValueMapper: (EvaluationLevelChart data, _) =>
                      data.translate,
                  color: hexStringToHexInt('#9d98f4'),
                  dataLabelSettings: DataLabelSettings(isVisible: false),
                ),
              ]
            : this.mode == 'benchmark'
                ? <ChartSeries>[
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Listening',
                      name: 'Listening'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.listening,
                      color: hexStringToHexInt('#ed5565'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Reading',
                      name: 'Reading'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.reading,
                      color: hexStringToHexInt('#23c6c8'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Speaking',
                      name: 'Speaking'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.speaking,
                      color: hexStringToHexInt('#f8ac59'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Writing',
                      name: 'Writing'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.writing,
                      color: hexStringToHexInt('#1ab394'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                  ]
                : <ChartSeries>[
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Listening',
                      name: 'Listening'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.listening,
                      color: hexStringToHexInt('#ed5565'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Reading',
                      name: 'Reading'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.reading,
                      color: hexStringToHexInt('#23c6c8'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Speaking',
                      name: 'Speaking'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.speaking,
                      color: hexStringToHexInt('#f8ac59'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'Writing',
                      name: 'Writing'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.writing,
                      color: hexStringToHexInt('#1ab394'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                    StackedLineSeries<EvaluationLevelChart, String>(
                      groupName: 'AISpeaking',
                      name: 'AI Speaking'.tr,
                      dashArray: <double>[5, 5],
                      dataSource: levelChartData,
                      xValueMapper: (EvaluationLevelChart data, _) =>
                          data.level.replaceAll('ACTFLLevel.', ''),
                      yValueMapper: (EvaluationLevelChart data, _) =>
                          data.aiSpeaking,
                      color: hexStringToHexInt('#9d98f4'),
                      dataLabelSettings: DataLabelSettings(isVisible: false),
                    ),
                  ]);
  }
}
